package app.controller.city;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import app.entity.Pager;
import app.entity.UserSession;
import app.service.FacilitiesManageService;
import app.utils.BasePathCollector;
import app.utils.Common;
import app.utils.DataResponse;
import siotwx.dao.DeviceDao;
import siotwx.dao.FacmonitoringDao;
import siotwx.dao.GroupDao;
import siotwx.dao.Group_facDao;
import siotwx.dao.Group_userDao;
import siotwx.dao.UserDao;
import siotwx.entity.Device;
import siotwx.entity.Facmonitoring;
import siotwx.entity.Group;
import siotwx.entity.Group_fac;
import siotwx.entity.Group_user;
import siotwx.entity.User;
@Controller
public class LogicAreaController {

	@Autowired
	@Qualifier("FacilitiesManageService")
	private FacilitiesManageService fms;
	
	@Autowired
	@Qualifier("GroupDao")
	private GroupDao groupDao;
	
	@Autowired
	@Qualifier("Group_facDao")
	private Group_facDao group_facDao;
	
	@Autowired
	@Qualifier("DeviceDao")
	private DeviceDao deviceDao;
	
	@Autowired
	@Qualifier("FacmonitoringDao")
	private FacmonitoringDao facmonitoringDao;
	
	@Autowired
	@Qualifier("Group_userDao")
	private Group_userDao group_userDao;
	
	@Autowired
	@Qualifier("UserDao")
	private UserDao userDao;
	
	//删除区域
	@RequestMapping("/area/del/{groupId}")
	public void delGroup(@PathVariable("groupId") Integer groupId,HttpServletResponse response){
		if (groupId!=null) {
			Map<String, Object> params=new HashMap<>();
			params.put(Group_fac.FieldName.is_deleted.toString(), 0);
			params.put(Group_fac.FieldName.group_id.toString(), groupId);
			Integer update = group_facDao.updateByCon(params,"is_deleted",1);
			
			//删除分组
			Group group = groupDao.get(groupId);
			group.setIs_deleted(true);
			Integer update2 = groupDao.update(group);
			
			if (update+update2>0) {
				DataResponse.jsonResponse(response, 1);
				return;
			}
		}else {
			DataResponse.jsonResponse(response, 0);
			return;
		}
	}
	
	//设置区域管理员
	@RequestMapping("/area/setuser/{user}/group/{groupId}")
	public void setUser(@PathVariable("user")Integer user,@PathVariable("groupId")Integer groupId, HttpServletResponse response){
		Map<String, Object> params=new HashMap<>();
		params.put(Group_user.FieldName.group_id.toString(), groupId);
		params.put(Group_user.FieldName.is_deleted.toString(), 0);
		List<Group_user> list = group_userDao.getlist(params);
		if (list!=null&&list.size()>0) {
			Group_user group_user = list.get(0);
			group_user.setIs_deleted(true);
			group_userDao.update(group_user);
			
			group_user=new Group_user(null, user, 0, groupId, System.currentTimeMillis(), false);
			Integer insert = group_userDao.insert(group_user);
			if (insert>0) {
				DataResponse.jsonResponse(response, insert);
			}else {
				DataResponse.jsonResponse(response, 0);
			}
		}else {
			Group_user group_user = new Group_user(null, user, 0, groupId, System.currentTimeMillis(), false);
			Integer insert = group_userDao.insert(group_user);
			if (insert>0) {
				DataResponse.jsonResponse(response, insert);
			}else {
				DataResponse.jsonResponse(response, 0);
			}
		}
	}
	
	@RequestMapping("/area/removeone/{fac}")
	public void
	removeOne(@PathVariable("fac")Integer fac, HttpServletResponse response){
		if (fac!=null&&!"".equals(fac)){
			Map<String, Object> params=new HashMap<>();
			params.put(Group_fac.FieldName.fac_id.toString(), fac);
			Integer deleteby = group_facDao.deleteby(params);
			if (deleteby>0) {
				DataResponse.jsonResponse(response, deleteby);
			}else {
				DataResponse.jsonResponse(response, 0);
			}
		}
	}
	
	//分页异步获取分组中的设施
	@RequestMapping("/area/facs/group/{groupId}/page/{pageNum}")
	public void facs(@PathVariable("groupId") Integer groupId, @PathVariable("pageNum") Integer pageNum,HttpServletResponse response){
		pageNum=(pageNum==null||pageNum<1)?1:pageNum;
		Map<String, Object> params=new HashMap<>();
		params.put(Group_fac.FieldName.group_id.toString(), groupId);
		params.put(Group_fac.FieldName.is_deleted.toString(), 0);
		Integer count = group_facDao.count(params);
		Pager pager=new Pager(count, pageNum,5);
		params.put("pager", pager);
		List<Group_fac> list = group_facDao.getlist(params);
		
		List<String> facs=new ArrayList<>();
		for(Group_fac group_fac:list){
			facs.add(group_fac.getFac_id()+"");
		}
		List<Facmonitoring> listByIn = facmonitoringDao.getListByIn(Facmonitoring.FieldName.facId.toString(), facs);
		
		//获取当前的区域的责任人
		Map<String, Object> param=new HashMap<>();
		param.put(Group_user.FieldName.group_id.toString(), groupId);
		param.put(Group_user.FieldName.is_deleted.toString(),0);
		List<Group_user> userList = group_userDao.getlist(param);
		params.clear();
		if (userList!=null&&userList.size()>0) {
			User user = userDao.get(userList.get(0).getUser_id());
			params.put("user", user);
		}else {
			params.put("user", new User(null,
					0, 0, 0, "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0L, "", "", "",""));
		}
		int index=(pageNum-1)*5;
		int total=pager.getItemtotal();
		int stop=(pageNum)*5<total?(pageNum)*5:total;
		List<Facmonitoring> res=new ArrayList<>();
		for(int i=0;i<listByIn.size();i++,index++){
			Facmonitoring facmonitoring = listByIn.get(i);
			facmonitoring.setEventId(index+1);
			res.add(facmonitoring);
		}
		
		params.put("list", res);
		params.put("pager", pager);
		DataResponse.jsonResponse(response, params);
	}
	
	
	//向指定分组中添加新的设施
	@RequestMapping("/area/add2group/{devCode}/group/{groupId}")
	public void addNewFac2Group(@PathVariable("devCode") String devCode,@PathVariable("groupId") Integer groupId,HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> params=new HashMap<>();
		params.put(Device.FieldName.code.toString(), devCode);
		List<Device> list = deviceDao.getlist(params);
		if (list!=null&&list.size()>0) {
			Device device = list.get(0);
			Integer facilities_id = device.getFacilities_id();
			Group_fac group_fac=new Group_fac(null,
					facilities_id,
					groupId, 
					System.currentTimeMillis(),
					false);
			Integer insert = group_facDao.insert(group_fac);
			DataResponse.jsonResponse(response, insert);
			return;
		}
		DataResponse.jsonResponse(response, 0);
		
	}
	
	//创建新的分组
	@RequestMapping("/area/newone/{regionId}/{groupName}")
	public void createGroup(@PathVariable("groupName") String groupName,@PathVariable("regionId")Integer regionId,HttpServletRequest request,HttpServletResponse response){
		Group group=new Group(null,
							  groupName,
							  regionId,
							  System.currentTimeMillis(),
							  false);
		Integer insert = groupDao.insert(group);
		DataResponse.jsonResponse(response, insert);
	}
	
	@RequestMapping("/chose/map")
	public String choseMap(String groupId,HttpServletRequest request,HttpSession session,Model model){
		
		model.addAttribute("basePath", BasePathCollector.getBasePathWithoutPort(request));
		//获取用户信息
		UserSession userSession = (UserSession)session.getAttribute(Common.sessionUser);
		int regionId = userSession.getRegionId();
		
		Map<String, Object> param=new HashMap<>();
		param.put(Group_fac.FieldName.is_deleted.toString(), 0);
		List<Group_fac> facList = group_facDao.getlist(param);
		List<String> facs=new ArrayList<>();
		for(Group_fac group_fac:facList){
			facs.add(group_fac.getFac_id()+"");
		}
		List<Facmonitoring> showlist = facmonitoringDao.getListByNotIn(regionId,"facId", facs);
		if (showlist!=null&&showlist.size()>0) {
			model.addAttribute("latitude", showlist.get(0).getFacLat());
			model.addAttribute("longitude", showlist.get(0).getFacLon());
		}else {
			model.addAttribute("latitude", null);
			model.addAttribute("longitude", null);
		}
		model.addAttribute("list", showlist);
		model.addAttribute("groupId", groupId);
		return "city/devicechosemap";
	}
}
